//
//  Loader.m
//  InTheSnow
//
//  Created by di on 7/30/09.
//  Copyright 2009 INTELLECTSOFT. All rights reserved.
//
#import "BannersParser.h"
#import "RSSParser.h"
#import <CFNetwork/CFNetwork.h>
#import "Loader.h"


@implementation Loader

@synthesize __parser;
@synthesize feedConnection;
@synthesize data;

- (id) initWithFeedType:(int)f parser:(<XMLParser>)parser
{ 
	self = [super init];
	if (self != nil) {
		feed = f;
		
		self.__parser = parser;
		 
		NSURLRequest *earthquakeURLRequest = [NSURLRequest requestWithURL:[parser isUrl]];
		self.feedConnection = [[[NSURLConnection alloc] initWithRequest:earthquakeURLRequest delegate:self] autorelease];
	 
		NSAssert(self.feedConnection != nil, @"Failure to create URL connection.");
	}
	return self;
}


- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
	self.data = [NSMutableData data];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data_ {
    [self.data appendData:data_];
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
    [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;   
    if ([error code] == kCFURLErrorNotConnectedToInternet) { 
        NSDictionary *userInfo = [NSDictionary dictionaryWithObject:NSLocalizedString(@"No Connection Error", @"Error message displayed when not connected to the Internet.") forKey:NSLocalizedDescriptionKey];
        NSError *noConnectionError = [NSError errorWithDomain:NSCocoaErrorDomain code:kCFURLErrorNotConnectedToInternet userInfo:userInfo];
        [self handleError:noConnectionError];
    } else {
		
		
		NSArray		*patchs = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
		NSString	*path	= [NSString stringWithString:[patchs objectAtIndex:0]];
		if(feed == 0)
		{	
			path = [path stringByAppendingPathComponent:@"local"];
			NSData *data_ = [NSData dataWithContentsOfFile:path];
			//		NSLog([data_ description]);
			RSSParser *parser = [[RSSParser alloc] init] ;    
			[parser parseData:data_];
			[parser release];		
			__delegate.isOffline = YES;
			// otherwise handle the error generically
			[self handleError:error];
			
		}else if(feed == 1)
		{
			
			if([__delegate isFirst])
			{
				[__delegate setIsFirst:NO];
				[__delegate afterFirstLoading];
			} 
		}
	} 
	
	[__parser release];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection { 
    [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;   
	NSArray		*patchs = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
	NSString	*path	= [NSString stringWithString:[patchs objectAtIndex:0]];
	if(feed == 0)
	{		 
		RSSParser *parser = [[RSSParser alloc] init] ;  
		NSString *s_ = [[NSString alloc] initWithData:self.data encoding:NSUTF8StringEncoding] ;
		NSData*dt_ = [[ s_  stringByReplacingOccurrencesOfString:@"&" withString:@"&amp;"] dataUsingEncoding:NSUTF8StringEncoding];
		[s_ release];
		[__parser parseData:dt_];
		[parser release];
	
	
		
		path = [path stringByAppendingPathComponent:@"local"];	
		[dt_ writeToFile:path atomically:YES]; 
	}else if (feed == 1) 
	{
		BannersParser *pb = [[BannersParser alloc] init];
		[__parser parseData:self.data];
		[pb release];	
		path = [path stringByAppendingPathComponent:@"banner"];	
		[data writeToFile:path atomically:YES]; 
		if([__delegate isFirst])
		{
			[__delegate setIsFirst:NO];
			[__delegate afterFirstLoading];
		}
	}
	
	[__parser release];
}
 
- (void)handleError:(NSError *)error {
    NSString *errorMessage = [error localizedDescription];
	errorMessage = [errorMessage stringByReplacingOccurrencesOfString:@"Error" withString:@" "];
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Check internet reachability"  message:errorMessage delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
    [alertView show];
    [alertView release];
	[[NSNotificationCenter defaultCenter] postNotificationName:@"norotate" object:nil];
}

- (void) dealloc
{ 
	[feedConnection release];
	[data release];
	[super dealloc];
}

@end
